<?php

namespace Admin\Controller;

use Think\Controller;

class FinanceController extends Controller
{
    public function myzr()
    {
        $list = M('Myzr')
            ->field('username,id,userid,num,addtime,status,coinname')
            ->order('id desc')
            ->select();

        foreach ($list as $k => $v) {
            $list[$k]['usernamea'] = M('User')->where(array(
                'id' => $v['userid']
            ))->getField('username');
        }

        $this->ajaxReturn($list, 'JSON');
    }

    public function myzc()
    {
        $list = M('Myzc')
            ->field('username,id,userid,num,addtime,status,coinname')
            ->order('id desc')
            ->select();

        foreach ($list as $k => $v) {
            $list[$k]['usernamea'] = M('User')->where(array(
                'id' => $v['userid']
            ))->getField('username');
        }

        $this->ajaxReturn($list, 'JSON');
    }

    public function myzcQueren($id = NULL)
    {
        $myzc = M('Myzc')->where(array(
            'id' => trim($id)
        ))->find();
        $addr = $myzc['username'];

        if (!$myzc) {
            $this->ajaxError('转出错误！');
        }

        if ($myzc['status']) {
            $this->ajaxError('已经处理过！');
        }

        $username = M('User')->where(array(
            'id' => $myzc['userid']
        ))->getField('username');
        $coin = $myzc['coinname'];
        $dj_username = C('coin')[$coin]['dj_yh'];
        $dj_password = C('coin')[$coin]['dj_mm'];
        $dj_address = C('coin')[$coin]['dj_zj'];
        $dj_port = C('coin')[$coin]['dj_dk'];

        if (C('coin')[$coin]['type'] == 'eth') {
            $eth = new \Common\Ext\Ethereum($dj_address, $dj_port);
            if (!$eth->eth_protocolVersion()) {
                $this->ajaxError('钱包链接失败！');
            }
        } else {
            $CoinClient = CoinClient($dj_username, $dj_password, $dj_address, $dj_port, 5, array(), 1);
            $json = $CoinClient->getinfo();
            if (!isset($json['version']) || !$json['version']) {
                $this->ajaxError('钱包链接失败！');
            }

            $valid_res = $CoinClient->validateaddress($addr);

            if (!$valid_res['isvalid']) {
                $this->ajaxError($addr . '不是一个有效的钱包地址！');
            }
        }


        $Coin = M('Coin')->where(array(
            'name' => $myzc['coinname']
        ))->find();
        $fee_user = M('UserCoin')->where(array(
            $coin . 'b' => $Coin['zc_user']
        ))->find();
        $user_coin = M('UserCoin')->where(array(
            'userid' => $myzc['userid']
        ))->find();
        $zhannei = M('UserCoin')->where(array(
            $coin . 'b' => $myzc['username']
        ))->find();
        $mo = M();
        $mo->execute('set autocommit=0');
        $mo->execute('lock tables  trade_user_coin write  , trade_myzc write  , trade_myzr write , trade_myzc_fee write, trade_sms write,trade_config write');
        $rs = array();

        if ($zhannei) {
            $rs[] = $mo->table('trade_myzr')->add(array(
                'userid' => $zhannei['userid'],
                'username' => $myzc['username'],
                'coinname' => $coin,
                'txid' => md5($myzc['username'] . $user_coin[$coin . 'b'] . time()),
                'num' => $myzc['num'],
                'fee' => $myzc['fee'],
                'mum' => $myzc['mum'],
                'addtime' => time(),
                'endtime' => time(),
                'status' => 1
            ));
            $rs[] = $r = $mo->table('trade_user_coin')
                ->where(array(
                    'userid' => $zhannei['userid']
                ))
                ->setInc($coin, $myzc['mum']);
        }

        if (!$fee_user['userid']) {
            $fee_user['userid'] = 0;
        }

        if (0 < $myzc['fee']) {
            $rs[] = $mo->table('trade_myzc_fee')->add(array(
                'userid' => $fee_user['userid'],
                'username' => $Coin['zc_user'],
                'coinname' => $coin,
                'num' => $myzc['num'],
                'fee' => $myzc['fee'],
                'mum' => $myzc['mum'],
                'type' => 2,
                'addtime' => time(),
                'status' => 1
            ));

            if ($mo->table('trade_user_coin')
                ->where(array(
                    $coin . 'b' => $Coin['zc_user']
                ))
                ->find()
            ) {
                $rs[] = $mo->table('trade_user_coin')
                    ->where(array(
                        $coin . 'b' => $Coin['zc_user']
                    ))
                    ->setInc($coin, $myzc['fee']);
                debug(array(
                    'lastsql' => $mo->table('trade_user_coin')->getLastSql()
                ), '新增费用');
            } else {
                $rs[] = $mo->table('trade_user_coin')->add(array(
                    $coin . 'b' => $Coin['zc_user'],
                    $coin => $myzc['fee']
                ));
            }
        }

        $rs[] = $mo->table('trade_myzc')
            ->where(array(
                'id' => trim($id)
            ))
            ->save(array(
                'status' => 1,
                'endtime' => time()
            ));

        if (check_arr($rs)) {
            switch (C('coin')[$coin]['type']) {
                case 'eth':
                    $transaction = new \Common\Ext\Ethereum_Transaction($Coin['dj_mian_address'], $myzc['username'], $eth->encode_dec($eth->to_real_value((double)$myzc['mum'])));
                    $sendrs = $eth->eth_sendTransaction($Coin['dj_mian_address'], $Coin['dj_mian_address_password'], $transaction);
                    if ($sendrs) {
                        $flag = 1;
                        // 记录txid
                        $rs[] = $mo->table('trade_myzc')
                            ->where(array(
                                'id' => trim($id)
                            ))
                            ->save(array(
                                'txid' => $sendrs
                            ));
                    } else {
                        $flag = 0;
                    }
                    break;
                case 'qbb':
                    $sendrs = $CoinClient->sendtoaddress($myzc['username'], (double)$myzc['mum']);
                    if ($sendrs) {
                        $flag = 1;
                        $arr = json_decode($sendrs, true);

                        if (isset($arr['status']) && ($arr['status'] == 0)) {
                            $flag = 0;
                        }
                        if (isset($arr['result']) && $arr['result'] != NULL) {
                            $flag = 1;
                            $rs[] = $mo->table('trade_myzc')
                                ->where(array(
                                    'id' => trim($id)
                                ))
                                ->save(array(
                                    'txid' => $arr['result']
                                ));
                        }
                    } else {
                        $flag = 0;
                    }
                    break;
            }

            if (!$flag) {
                $mo->execute('rollback');
                $mo->execute('unlock tables');
                $this->ajaxError('钱包服务器转出币失败!');
            } else {
                $mo->execute('commit');
                $mo->execute('unlock tables');
                $this->ajaxSuccess('转账成功！');
            }
        } else {
            $mo->execute('rollback');
            $mo->execute('unlock tables');
            $this->ajaxError('转出失败!' . implode('|', $rs) . $myzc['fee']);
        }
    }
}

?>